﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace LibraryApi.Common
{
    internal class ObjectSerializer
    {
        private readonly IFormatter m_Formatter;

        public ObjectSerializer()
        {
            m_Formatter = new BinaryFormatter();
        }

        public byte[] Serialize<T>(T @object)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                m_Formatter.Serialize(memory, @object);
                return memory.ToArray();
            }
        }

        public T Deserialize<T>(byte[] buffer)
        {
            using (MemoryStream memory = new MemoryStream(buffer))
            {
                T @object = (T)m_Formatter.Deserialize(memory);
                return @object;
            }
        }

        public T Deserialize<T>(byte[] buffer, int length)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                memory.Write(buffer, 0, length);
                T @object = (T)m_Formatter.Deserialize(memory);
                return @object;
            }
        }

        public static T Load<T>(byte[] data)
        {
            if (data == null)
                throw new ArgumentException("data");

            ObjectSerializer serializer = new ObjectSerializer();
            return serializer.Deserialize<T>(data);
        }

        public static byte[] Save<T>(T @object)
        {
            if (@object == null)
                throw new ArgumentException("@object");

            ObjectSerializer serializer = new ObjectSerializer();
            return serializer.Serialize<T>(@object);
        }
    }
}
